#include "productbrowsepage.h"
#include <QApplication>
#include <QDebug>

// 样式常量定义
const QString ProductBrowsePage::MAIN_STYLE = 
    "QWidget { "
    "    background-color: #f0f8f0; "
    "    font-family: 'Microsoft YaHei'; "
    "    font-size: 12px; "
    "}";

const QString ProductBrowsePage::GROUP_STYLE = 
    "QGroupBox { "
    "    font-weight: bold; "
    "    border: 2px solid #4CAF50; "
    "    border-radius: 8px; "
    "    margin-top: 10px; "
    "    background-color: white; "
    "    padding-top: 15px; "
    "} "
    "QGroupBox::title { "
    "    subcontrol-origin: margin; "
    "    left: 15px; "
    "    padding: 0 8px 0 8px; "
    "    color: #2E7D32; "
    "    font-size: 14px; "
    "    background-color: white; "
    "}";

const QString ProductBrowsePage::TABLE_STYLE = 
    "QTableWidget { "
    "    gridline-color: #c8e6c9; "
    "    background-color: white; "
    "    alternate-background-color: #f1f8e9; "
    "    selection-background-color: #66BB6A; "
    "    border: 1px solid #4CAF50; "
    "    border-radius: 5px; "
    "} "
    "QTableWidget::item { "
    "    padding: 8px; "
    "    border-bottom: 1px solid #e8f5e8; "
    "} "
    "QTableWidget::item:selected { "
    "    color: white; "
    "} "
    "QHeaderView::section { "
    "    background-color: #4CAF50; "
    "    color: white; "
    "    padding: 10px; "
    "    border: none; "
    "    border-right: 1px solid #45a049; "
    "    font-weight: bold; "
    "    font-size: 13px; "
    "}";

const QString ProductBrowsePage::BUTTON_STYLE = 
    "QPushButton { "
    "    background-color: #4CAF50; "
    "    color: white; "
    "    border: none; "
    "    padding: 8px 16px; "
    "    border-radius: 4px; "
    "    font-weight: bold; "
    "} "
    "QPushButton:hover { "
    "    background-color: #45a049; "
    "} "
    "QPushButton:pressed { "
    "    background-color: #3d8b40; "
    "}";

const QString ProductBrowsePage::SEARCH_STYLE = 
    "QLineEdit, QComboBox { "
    "    padding: 8px 12px; "
    "    border: 2px solid #c8e6c9; "
    "    border-radius: 6px; "
    "    background-color: white; "
    "    font-size: 13px; "
    "} "
    "QLineEdit:focus, QComboBox:focus { "
    "    border-color: #4CAF50; "
    "    background-color: #f9fff9; "
    "} "
    "QComboBox::drop-down { "
    "    border: none; "
    "    background-color: #4CAF50; "
    "    border-radius: 3px; "
    "} "
    "QComboBox::down-arrow { "
    "    image: none; "
    "    border: 2px solid white; "
    "    width: 0; "
    "    height: 0; "
    "    border-top: 4px solid white; "
    "    border-left: 4px solid transparent; "
    "    border-right: 4px solid transparent; "
    "}";

ProductBrowsePage::ProductBrowsePage(ProductDAO* productDao, QWidget *parent)
    : QWidget(parent)
    , m_productDao(productDao)
    , m_selectedProductId(-1)
{
    // 初始化业务服务
    m_service = new ProductBrowseService(m_productDao, this);
    
    // 初始化搜索定时器
    m_searchTimer = new QTimer(this);
    m_searchTimer->setSingleShot(true);
    m_searchTimer->setInterval(500); // 500ms延迟
    
    // 初始化UI
    initUI();
    setupConnections();
    applyStyles();
    
    // 加载初始数据
    loadCategories();
    refreshData();
}

ProductBrowsePage::~ProductBrowsePage()
{
    // 服务对象会被Qt自动清理
}

void ProductBrowsePage::initUI()
{
    // 创建主布局
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(15, 15, 15, 15);
    m_mainLayout->setSpacing(15);
    
    // 设置搜索区域
    setupSearchArea();
    
    // 创建内容分割器
    m_contentSplitter = new QSplitter(Qt::Horizontal, this);
    
    // 设置商品列表区域
    setupProductTable();
    
    // 设置详情区域
    setupDetailArea();
    
    // 添加到分割器
    m_contentSplitter->addWidget(m_listGroup);
    m_contentSplitter->addWidget(m_detailGroup);
    m_contentSplitter->setStretchFactor(0, 2); // 列表占2/3
    m_contentSplitter->setStretchFactor(1, 1); // 详情占1/3
    
    // 添加到主布局
    m_mainLayout->addWidget(m_searchGroup);
    m_mainLayout->addWidget(m_contentSplitter, 1); // 内容区域占满剩余空间
}

void ProductBrowsePage::setupSearchArea()
{
    m_searchGroup = new QGroupBox("🔍 搜索和筛选", this);
    m_searchGroup->setFixedHeight(120); // 固定高度120px
    m_searchLayout = new QHBoxLayout(m_searchGroup);
    m_searchLayout->setContentsMargins(20, 25, 20, 15);
    m_searchLayout->setSpacing(15);
    
    // 搜索框
    m_searchEdit = new QLineEdit(this);
    m_searchEdit->setPlaceholderText("🔍 输入商品名称搜索...");
    m_searchEdit->setMinimumWidth(220);
    m_searchEdit->setFixedHeight(36);
    
    // 搜索按钮
    m_searchBtn = new QPushButton("🔍 搜索", this);
    m_searchBtn->setFixedSize(90, 36);
    
    // 清空按钮
    m_clearBtn = new QPushButton("🗑️ 清空", this);
    m_clearBtn->setFixedSize(90, 36);
    
    // 分类筛选
    QLabel* categoryLabel = new QLabel("📂 分类:", this);
    categoryLabel->setStyleSheet("color: #2E7D32; font-weight: bold; font-size: 13px;");
    m_categoryCombo = new QComboBox(this);
    m_categoryCombo->setMinimumWidth(160);
    m_categoryCombo->setFixedHeight(36);
    
    // 刷新按钮
    m_refreshBtn = new QPushButton("🔄 刷新", this);
    m_refreshBtn->setFixedSize(90, 36);
    
    // 添加到布局
    QLabel* searchLabel = new QLabel("🔍 搜索:", this);
    searchLabel->setStyleSheet("color: #2E7D32; font-weight: bold; font-size: 13px;");
    m_searchLayout->addWidget(searchLabel);
    m_searchLayout->addWidget(m_searchEdit);
    m_searchLayout->addWidget(m_searchBtn);
    m_searchLayout->addWidget(m_clearBtn);
    m_searchLayout->addSpacing(30);
    m_searchLayout->addWidget(categoryLabel);
    m_searchLayout->addWidget(m_categoryCombo);
    m_searchLayout->addSpacing(30);
    m_searchLayout->addWidget(m_refreshBtn);
    m_searchLayout->addStretch();
}

void ProductBrowsePage::setupProductTable()
{
    m_listGroup = new QGroupBox("📦 商品列表", this);
    QVBoxLayout* listLayout = new QVBoxLayout(m_listGroup);
    listLayout->setContentsMargins(15, 20, 15, 15);
    listLayout->setSpacing(12);
    
    // 统计标签
    m_countLabel = new QLabel("📊 共 0 件商品", this);
    m_countLabel->setStyleSheet(
        "QLabel {"
        "    font-weight: bold;"
        "    color: #2E7D32;"
        "    font-size: 14px;"
        "    padding: 8px 12px;"
        "    background-color: #E8F5E8;"
        "    border: 1px solid #A5D6A7;"
        "    border-radius: 6px;"
        "}"
    );
    
    // 创建表格
    m_productTable = new QTableWidget(this);
    setupTableHeaders();
    
    // 设置表格属性
    m_productTable->setAlternatingRowColors(true);
    m_productTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_productTable->setSelectionMode(QAbstractItemView::SingleSelection);
    m_productTable->setSortingEnabled(true);
    m_productTable->verticalHeader()->setVisible(false);
    
    // 设置默认排序（按商品ID升序）
    m_productTable->sortItems(0, Qt::AscendingOrder);
    
    // 设置表头可点击
    m_productTable->horizontalHeader()->setSectionsClickable(true);
    m_productTable->horizontalHeader()->setHighlightSections(true);
    
    // 美化表格样式
    m_productTable->setStyleSheet(
        "QTableWidget {"
        "    gridline-color: #C8E6C9;"
        "    background-color: white;"
        "    alternate-background-color: #F1F8E9;"
        "    selection-background-color: #A5D6A7;"
        "    border: 1px solid #81C784;"
        "    border-radius: 8px;"
        "}"
        "QTableWidget::item {"
        "    padding: 8px;"
        "    border-bottom: 1px solid #E0E0E0;"
        "}"
        "QTableWidget::item:selected {"
        "    background-color: #C8E6C9;"
        "    color: #1B5E20;"
        "}"
        "QHeaderView::section {"
        "    background-color: #4CAF50;"
        "    color: white;"
        "    padding: 10px 15px 10px 10px;"
        "    border: none;"
        "    font-weight: bold;"
        "    font-size: 13px;"
        "    text-align: left;"
        "}"
        "QHeaderView::section:hover {"
        "    background-color: #66BB6A;"
        "    cursor: pointer;"
        "}"
        "QHeaderView::up-arrow {"
        "    image: none;"
        "    border-left: 4px solid transparent;"
        "    border-right: 4px solid transparent;"
        "    border-bottom: 6px solid white;"
        "    width: 0px;"
        "    height: 0px;"
        "}"
        "QHeaderView::down-arrow {"
        "    image: none;"
        "    border-left: 4px solid transparent;"
        "    border-right: 4px solid transparent;"
        "    border-top: 6px solid white;"
        "    width: 0px;"
        "    height: 0px;"
        "}"
    );
    
    listLayout->addWidget(m_countLabel);
    listLayout->addWidget(m_productTable);
}

void ProductBrowsePage::setupDetailArea()
{
    m_detailGroup = new QGroupBox("📋 商品详情", this);
    QVBoxLayout* detailLayout = new QVBoxLayout(m_detailGroup);
    detailLayout->setContentsMargins(15, 20, 15, 15);
    detailLayout->setSpacing(15);
    
    // 商品图片标签（预留）
    m_productImageLabel = new QLabel(this);
    m_productImageLabel->setFixedHeight(120);
    m_productImageLabel->setAlignment(Qt::AlignCenter);
    m_productImageLabel->setStyleSheet(
        "QLabel {"
        "    border: 2px dashed #81C784;"
        "    background-color: #F1F8E9;"
        "    color: #4CAF50;"
        "    font-size: 13px;"
        "    border-radius: 8px;"
        "}"
    );
    m_productImageLabel->setText("🖼️ 商品图片\n(功能开发中)");
    
    // 详情文本
    m_detailText = new QTextEdit(this);
    m_detailText->setReadOnly(true);
    m_detailText->setPlainText("📝 请选择商品查看详细信息");
    m_detailText->setStyleSheet(
        "QTextEdit {"
        "    background-color: white;"
        "    border: 1px solid #81C784;"
        "    border-radius: 8px;"
        "    padding: 15px;"
        "    font-size: 17px;"
        "    line-height: 1.8;"
        "    font-family: 'Microsoft YaHei', 'SimHei', sans-serif;"
        "}"
        "QScrollBar:vertical {"
        "    background-color: #E8F5E8;"
        "    width: 12px;"
        "    border-radius: 6px;"
        "}"
        "QScrollBar::handle:vertical {"
        "    background-color: #81C784;"
        "    border-radius: 6px;"
        "    min-height: 20px;"
        "}"
        "QScrollBar::handle:vertical:hover {"
        "    background-color: #66BB6A;"
        "}"
    );
    
    detailLayout->addWidget(m_productImageLabel);
    detailLayout->addWidget(m_detailText);
}

void ProductBrowsePage::setupConnections()
{
    // 搜索相关连接
    connect(m_searchEdit, &QLineEdit::textChanged, this, [this]() {
        m_searchTimer->start(); // 重启定时器
    });
    connect(m_searchTimer, &QTimer::timeout, this, &ProductBrowsePage::performDelayedSearch);
    connect(m_searchBtn, &QPushButton::clicked, this, &ProductBrowsePage::searchProducts);
    connect(m_clearBtn, &QPushButton::clicked, this, &ProductBrowsePage::clearSearch);
    
    // 分类筛选
    connect(m_categoryCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &ProductBrowsePage::filterByCategory);
    
    // 刷新按钮
    connect(m_refreshBtn, &QPushButton::clicked, this, &ProductBrowsePage::refreshProductList);
    
    // 表格点击事件
    connect(m_productTable, &QTableWidget::cellClicked, this, &ProductBrowsePage::showProductDetail);
    
    // 表格排序事件
    connect(m_productTable->horizontalHeader(), &QHeaderView::sectionClicked, 
            this, [this](int logicalIndex) {
                // 排序后更新统计信息
                QTimer::singleShot(100, this, [this]() {
                    updateCountLabel(m_productTable->rowCount());
                });
            });
    
    // 服务层信号
    connect(m_service, &ProductBrowseService::errorOccurred, this, &ProductBrowsePage::handleServiceError);
}

void ProductBrowsePage::applyStyles()
{
    this->setStyleSheet(MAIN_STYLE);
    m_searchGroup->setStyleSheet(GROUP_STYLE);
    m_listGroup->setStyleSheet(GROUP_STYLE);
    m_detailGroup->setStyleSheet(GROUP_STYLE);
    m_productTable->setStyleSheet(TABLE_STYLE);
    
    // 按钮样式
    m_searchBtn->setStyleSheet(BUTTON_STYLE);
    // 为清除按钮设置样式：先复制常量字符串，再修改副本
    QString clearBtnStyle = BUTTON_STYLE;
    clearBtnStyle.replace("#4CAF50", "#f44336")
                 .replace("#45a049", "#da190b")
                 .replace("#3d8b40", "#b71c1c");
    m_clearBtn->setStyleSheet(clearBtnStyle);

    // 为刷新按钮设置样式：同样先复制常量字符串，再修改副本
    QString refreshBtnStyle = BUTTON_STYLE;
    refreshBtnStyle.replace("#4CAF50", "#2196F3")
                   .replace("#45a049", "#1976D2")
                   .replace("#3d8b40", "#0D47A1");
    m_refreshBtn->setStyleSheet(refreshBtnStyle);
    
    // 搜索框样式
    m_searchEdit->setStyleSheet(SEARCH_STYLE);
    m_categoryCombo->setStyleSheet(SEARCH_STYLE);
}

void ProductBrowsePage::setupTableHeaders()
{
    QStringList headers;
    headers << "商品ID" << "商品名称" << "规格" << "颜色" << "供应商" 
            << "采购价" << "零售价" << "分类" << "库存" << "会员折扣" << "创建时间";
    
    m_productTable->setColumnCount(headers.size());
    m_productTable->setHorizontalHeaderLabels(headers);
    
    // 调整列宽
    resizeTableColumns();
}

void ProductBrowsePage::resizeTableColumns()
{
    QHeaderView* header = m_productTable->horizontalHeader();
    header->setStretchLastSection(true);
    
    // 设置各列的宽度
    m_productTable->setColumnWidth(0, 80);   // ID
    m_productTable->setColumnWidth(1, 150);  // 名称
    m_productTable->setColumnWidth(2, 100);  // 规格
    m_productTable->setColumnWidth(3, 80);   // 颜色
    m_productTable->setColumnWidth(4, 120);  // 供应商
    m_productTable->setColumnWidth(5, 80);   // 采购价
    m_productTable->setColumnWidth(6, 80);   // 零售价
    m_productTable->setColumnWidth(7, 100);  // 分类
    m_productTable->setColumnWidth(8, 80);   // 库存
    m_productTable->setColumnWidth(9, 80);   // 会员折扣
    // 最后一列（创建时间）自动拉伸
}

void ProductBrowsePage::loadCategories()
{
    m_allCategories = m_service->getAllCategories();
    
    m_categoryCombo->clear();
    m_categoryCombo->addItem("全部分类", -1);
    
    for (const auto& category : m_allCategories) {
        QString name = category["category_name"].toString();
        int id = category["category_id"].toInt();
        m_categoryCombo->addItem(name, id);
    }
}

void ProductBrowsePage::refreshData()
{
    m_currentProducts = m_service->getAllProductsWithCategory();
    populateProductTable(m_currentProducts);
}

void ProductBrowsePage::populateProductTable(const QVector<QMap<QString, QVariant>>& products)
{
    // 临时禁用排序以提高性能
    bool sortingEnabled = m_productTable->isSortingEnabled();
    m_productTable->setSortingEnabled(false);
    
    m_productTable->setRowCount(products.size());
    
    for (int row = 0; row < products.size(); ++row) {
        const auto& product = products[row];
        
        m_productTable->setItem(row, 0, createTableItem(product["product_id"].toString()));
        m_productTable->setItem(row, 1, createTableItem(product["product_name"].toString()));
        m_productTable->setItem(row, 2, createTableItem(product["specification"].toString()));
        m_productTable->setItem(row, 3, createTableItem(product["color"].toString()));
        m_productTable->setItem(row, 4, createTableItem(product["supplier"].toString()));
        m_productTable->setItem(row, 5, createTableItem(m_service->formatPrice(product["purchase_price"].toDouble())));
        m_productTable->setItem(row, 6, createTableItem(m_service->formatPrice(product["selling_price"].toDouble())));
        m_productTable->setItem(row, 7, createTableItem(product["category_name"].toString()));
        m_productTable->setItem(row, 8, createTableItem(product["stock_quantity"].toString()));
        m_productTable->setItem(row, 9, createTableItem(product["allow_member_discount"].toBool() ? "是" : "否"));
        m_productTable->setItem(row, 10, createTableItem(product["create_time"].toDateTime().toString("yyyy-MM-dd hh:mm")));
    }
    
    // 恢复排序功能
    m_productTable->setSortingEnabled(sortingEnabled);
    
    updateCountLabel(products.size());
}

QTableWidgetItem* ProductBrowsePage::createTableItem(const QString& text)
{
    QTableWidgetItem* item = new QTableWidgetItem(text);
    item->setFlags(item->flags() & ~Qt::ItemIsEditable); // 只读
    return item;
}

void ProductBrowsePage::updateCountLabel(int count)
{
    // 统计库存状态
    int lowStockCount = 0;
    int outOfStockCount = 0;
    
    for (int row = 0; row < m_productTable->rowCount(); ++row) {
        QTableWidgetItem* stockItem = m_productTable->item(row, 8); // 库存列
        if (stockItem) {
            int stock = stockItem->text().toInt();
            if (stock <= 0) {
                outOfStockCount++;
            } else if (stock <= 10) {
                lowStockCount++;
            }
        }
    }
    
    QString statusText = QString("📊 共 %1 件商品").arg(count);
    if (outOfStockCount > 0) {
        statusText += QString(" | ❌ 缺货: %1 件").arg(outOfStockCount);
    }
    if (lowStockCount > 0) {
        statusText += QString(" | ⚠️ 库存不足: %1 件").arg(lowStockCount);
    }
    if (outOfStockCount == 0 && lowStockCount == 0 && count > 0) {
        statusText += " | ✅ 库存状态良好";
    }
    
    m_countLabel->setText(statusText);
}

void ProductBrowsePage::searchProducts()
{
    QString searchText = m_searchEdit->text().trimmed();
    
    if (searchText.isEmpty()) {
        refreshData();
    } else {
        QVector<QMap<QString, QVariant>> results = m_service->searchProductsByName(searchText);
        populateProductTable(results);
    }
}

void ProductBrowsePage::filterByCategory()
{
    int categoryId = m_categoryCombo->currentData().toInt();
    
    if (categoryId == -1) {
        // 显示全部
        refreshData();
    } else {
        QVector<QMap<QString, QVariant>> results = m_service->getProductsByCategory(categoryId);
        populateProductTable(results);
    }
}

void ProductBrowsePage::clearSearch()
{
    m_searchEdit->clear();
    m_categoryCombo->setCurrentIndex(0); // 选择"全部分类"
    refreshData();
}

void ProductBrowsePage::refreshProductList()
{
    loadCategories();
    refreshData();
    m_detailText->setPlainText("📝 请选择商品查看详细信息");
    m_selectedProductId = -1;
}

void ProductBrowsePage::showProductDetail(int row, int column)
{
    Q_UNUSED(column)
    
    if (row < 0 || row >= m_productTable->rowCount()) {
        return;
    }
    
    // 获取商品ID
    QTableWidgetItem* idItem = m_productTable->item(row, 0);
    if (!idItem) {
        return;
    }
    
    int productId = idItem->text().toInt();
    setSelectedProduct(productId);
}

void ProductBrowsePage::setSelectedProduct(int productId)
{
    m_selectedProductId = productId;
    
    QMap<QString, QVariant> product = m_service->getProductDetailById(productId);
    updateProductDetail(product);
}

void ProductBrowsePage::updateProductDetail(const QMap<QString, QVariant>& product)
{
    if (product.isEmpty()) {
        m_detailText->setPlainText("无法获取商品详情");
        return;
    }
    
    QString detailInfo = m_service->formatProductInfo(product);
    m_detailText->setPlainText(detailInfo);
}

void ProductBrowsePage::performDelayedSearch()
{
    searchProducts();
}

void ProductBrowsePage::handleServiceError(const QString& error)
{
    QMessageBox::warning(this, "错误", error);
    qWarning() << "ProductBrowsePage Service Error:" << error;
}
